const router=require('koa-router')();
const {User,Archive}=require('../models/index');
const {post:postProxy}=require('../proxy/index');
const Page=require('../lib/page');
const checkPage=require('../middlewares/checkPage');

//archives
router.get('/',async ctx=>{
    let [archives,noRelies,top10]=await Promise.all([
        Archive.find({},{archive:true,count:true},{sort:{archive:-1}}),
        postProxy.getList({comments:{$size:0}},null,{limit:5}),
        User.find(null,{name:true,score:true},{skip:0,limit:5,sort:{score:-1}})
    ]);
    let list=await Promise.all(archives.map(archive=>{
        //console.log('archive:',archive);//{ archive: '2017-11' }
        //不可以直接使用archive对象作为查询参数，因为archive中有其它不可见属性
        return postProxy.getList({archive:archive.archive},{intro:false,reprintUsers:false,pv:false,comments:false,tags:false});
    }));
    let groups=[];
    list.forEach((item,i)=>{
        if(item.total<=0)return;//无数据
        groups.push({
            archive:archives[i].archive,
            posts:item.posts,
            more:item.total>1?'/archives/'+archives[i].archive:false
        });
    });

    await ctx.render('archives',{
        title:'Archives',
        groups:groups,
        noReplies:noRelies.posts,
        top10,
        loginUser:ctx.session.loginUser,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});


router.get('/:date',checkPage(),async ctx=>{
    let date=ctx.params.date;
    if(!/2\d{3}\-\d{2}/.test(date) || Number.isNaN(new Date(date))){
        ctx.flash={error:'日期非法'};
        return ctx.redirect('back');
    }
    let start=new Date(date),end=new Date(start.getFullYear(),start.getMonth()+1,1);
    let [{total,page,posts},noReplies,top10]=await Promise.all([
        postProxy.getList({time:{$gte:start,$lt:end}},null,{page:ctx.query.p}),
        postProxy.getList({comments:{$size:0}},null,{limit:5}),
        User.find(null,{name:true,socre:true},{skip:0,limit:5,sort:{score:-1}})
    ]);

    await ctx.render('postList',{
        title:'Archive:'+date,
        loginUser:ctx.session.loginUser,
        top10,
        noReplies,
        success:ctx.flash.success,
        error:ctx.flash.error,
        posts:posts,
        page:Page(ctx.query,page,total)
    });
});

module.exports=router;